<?php


namespace EchoPHP\Database\Exceptions;

use EchoPHP\Support\Str;
use Exception;
use RuntimeException;

class QueryException extends RuntimeException {

    protected $sql;

    protected $bindings;

    public function __construct($sql, array $bindings, Exception $previous) {
        parent::__construct('', 0, $previous);

        $this->sql = $sql;
        $this->bindings = $bindings;
        $this->code = $previous->code;
        $this->message = $this->formatMessage($sql, $bindings, $previous);
    }

    /**
     * 格式化返回错误信息,拼接实际sql语句
     * @param $sql
     * @param $bindings
     * @param Exception $previous
     * @return string
     */
    protected function formatMessage($sql, $bindings, Exception $previous) {
        return $previous->getMessage() . '[ExecuteSQL: ' . Str::replaceArray('?', $bindings, $sql) . ']';
    }

    /**
     * 获取sql语句
     * @return mixed
     */
    public function getSql() {
        return $this->sql;
    }

    /**
     * 获取绑定变量
     * @return array
     */
    public function getBindings() {
        return $this->bindings;
    }
}